import logging
from django.views import View
from django_redis import get_redis_connection
from django import http
from random import randint


from mall_30.libs.captcha.captcha import captcha
from mall_30.utils.response_code import RETCODE
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.
logger = logging.getLogger('django')

class ImageCodeView(View):
    """发送图形验证码"""

    def get(self, request, uuid):


        # 利用SDK 生成图形验证码 (唯一标识字符串, 图形验证内容字符串, 二进制图片数据)
        name, text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection('verify_code')

        redis_conn.setex('img_%s'%uuid, 300, text)

        # 响应
        return http.HttpResponse(image, content_type='image/png')



class SMSCodeView(View):
    """短信验证码校验"""

    def get(self, request, mobile):

        redis_conn = get_redis_connection('verify_code')

        sending_flag = redis_conn.get('send_flag_%s' % mobile)

        if sending_flag:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '频繁发送短信'})

        #获取参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('uuid')

        #校验
        if all([image_code, uuid]) is False:
            return http.HttpResponseForbidden('缺少必传的参数')


        image_code_redis = redis_conn.get('img_%s'%uuid)

        if image_code_redis.decode().lower() != image_code.lower():
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR, 'errmsg': '验证码有误'})

        # 生成短信验证码
        sms_code = '%06d'%randint(0, 999999)
        logger.info(sms_code)

        pl = redis_conn.pipeline()

        pl.setex('sms_code_%s'%mobile, 300, sms_code)
        pl.setex('send_flag_%s'%mobile, 300, 1)

        pl.execute()

        #调用celery异步发送短信
        send_sms_code.delay(mobile, sms_code)

        #响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '短信验证码发送成功'})

